package br.ufpb.di.ppgi.persistencia.em;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import br.com.caelum.vraptor.ioc.ApplicationScoped;
import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.ioc.ComponentFactory;
import br.ufpb.di.ppgi.util.logger.Logger;
import br.ufpb.di.ppgi.util.logger.LoggerFactory;

@Component
@ApplicationScoped
@SuppressWarnings("unused")
public class EntityManagerFactoryCreator implements ComponentFactory<EntityManagerFactory> {
	private static final Logger LOGGER = LoggerFactory.getLogger(EntityManagerFactoryCreator.class);
	private EntityManagerFactory factory;

	public EntityManagerFactoryCreator() {}
	
	@Override
	public EntityManagerFactory getInstance() {
		return factory;
	}	
	
	@PostConstruct
	private void construct() {
		LOGGER.customDebug("Construindo a fábrica de EntityManager do provedor de persistencia.");
		factory = Persistence.createEntityManagerFactory("ppgi");
		LOGGER.customDebug("Fábrica de EntityManager do provedor de persistencia construido com sucesso.");
	}
	



	@PreDestroy
	private void destroy() {
		if (factory != null && factory.isOpen()) {
			LOGGER.customDebug("Destruindo a fábrica de EntityManager do provedor de persistencia [ThreadID %d].", Thread.currentThread().getId());
			factory.close();
			LOGGER.customDebug("Fábrica de EntityManager do provedor de persistencia destruida com sucesso.");
		}
		factory = null;
	}
	
}
